package buildTree;

import util.TreeNode;

/**
 * @program: javase
 * @description: 根据层次遍历的数组构造满二叉树
 * @author: luolidong
 * @create: 2021-06-18 21:23
 * @version: 1.0
 */
public class BuildTreeByArray {
    public TreeNode buildTree(int[] arr) {
//        保存树节点
        TreeNode[] treeNodes = new TreeNode[arr.length];
        for (int i = 0; i < arr.length; i++) {
            treeNodes[i] = new TreeNode(arr[i]);
        }
//        构造
        for (int i = 0; i < arr.length; i++) {
            if (2 * i + 1 < arr.length) {
                treeNodes[i].left = treeNodes[2 * i + 1];
            }
            if (2 * i + 2 < arr.length) {
                treeNodes[i].right = treeNodes[2 * i + 2];
            }
        }
        return treeNodes[0];
    }
    public static void main(String[] args) {
        TreeNode node = new BuildTreeByArray().buildTree(new int[]{1,2,3,4,5,6});
        System.out.println(node);
    }
}
